<template>
  <div class="exercise-bank-container">
    <div class="page-header">
      <h2>练习题库管理</h2>
      <p>课程ID：{{ courseId }}</p>
    </div>

    <!-- 添加题目表单（增加选择题选项支持） -->
    <div class="add-question-form">
      <h3>添加新题目</h3>
      <form @submit.prevent="handleAddQuestion">
        <div class="form-group">
          <label>题目内容</label>
          <textarea 
            v-model="newQuestion.questionContent" 
            class="form-control" 
            rows="3" 
            required
            @input="handleQuestionContentInput"
          />
        </div>

        <!-- 选择题选项区域 -->
        <div
          v-if="newQuestion.type === false"
          class="form-group"
        >
          <label>选择题选项（至少2个）</label>
          <div
            v-for="(option, index) in newQuestion.options"
            :key="index"
            class="input-group mb-2"
          >
            <span class="input-group-text">{{ getOptionLabel(index) }}</span>
            <input 
              v-model="newQuestion.options[index]" 
              type="text" 
              class="form-control" 
              required
              @input="handleOptionInput" 
            >
            <button 
              v-if="newQuestion.options.length > 2" 
              type="button" 
              class="btn btn-danger ms-2" 
              @click="removeOption(index)"
            >
              删除选项
            </button>
          </div>
          <button 
            type="button" 
            class="btn btn-primary mt-2" 
            @click="addOption"
          >
            添加选项
          </button>
        </div>

        <div class="form-group">
          <label>题目答案</label>
          <input 
            v-model="newQuestion.questionAnswer" 
            class="form-control" 
            required
          >
        </div>

        <div class="form-group">
          <label>题目类型</label>
          <select 
            v-model="newQuestion.type" 
            class="form-control" 
            required
            @change="handleTypeChange"
          >
            <option value="false">
              选择题
            </option>
            <option value="true">
              主观题
            </option>
          </select>
        </div>

        <div class="form-group">
          <label>题目分值</label>
          <input 
            v-model="newQuestion.questionScore" 
            type="number" 
            class="form-control" 
            min="1" 
            required
          >
        </div>

        <button 
          type="submit" 
          class="btn btn-primary" 
          :disabled="isLoading"
        >
          {{ isLoading ? '加载中...' : '添加题目' }}
        </button>
      </form>
    </div>

    <!-- 题目列表 -->
    <div class="question-list">
      <h3>题库题目列表（共 {{ questions.length }} 题）</h3>
      <ul class="list-group">
        <li 
          v-for="question in questions" 
          :key="question.questionId" 
          class="list-group-item"
        >
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <h5>{{ question.questionContent }}</h5>
              <p>
                类型：{{ question.type ? '主观题' : '选择题' }} | 
                分值：{{ question.questionScore }} 分
              </p>
            </div>
            <div>
              <button 
                class="btn btn-danger btn-sm" 
                :disabled="isLoading"
                @click="handleDeleteQuestion(question.questionId)"
              >
                删除
              </button>
              <input
                v-model="selectedQuestionIds"
                type="checkbox"
                :value="question.questionId"
                class="ml-2"
              >
            </div>
          </div>
        </li>
      </ul>
    </div>

    <!-- 发布练习面板 -->
    <div
      v-show="isPublishPanelOpen"
      class="publish-exercise-panel"
    >
      <h3 class="mb-4">
        发布练习
      </h3>
      <!-- 新增班级选择框 -->
      <div class="mb-3">
        <label class="form-label">选择班级</label>
        <select
          v-model="selectedClassId"
          class="form-control"
          :disabled="!classes.length"
          required
          @change="isPublishTouched = true"
        >
          <option value="">
            请选择班级
          </option>
          <option
            v-for="cls in classes"
            :key="cls.classesId"
            :value="cls.classesId"
          >
            {{ cls.classesName }}
          </option>
        </select>
        <div
          v-if="!selectedClassId && isPublishTouched"
          class="text-danger mt-1"
        >
          请选择要发布练习的班级
        </div>
      </div>
      <form @submit.prevent="handlePublish">
        <div class="mb-3">
          <label class="form-label">练习名称</label>
          <input 
            v-model="publishForm.exerciseName" 
            type="text" 
            class="form-control" 
            required
            @input="isPublishTouched = true"
          >
          <div
            v-if="!publishForm.exerciseName.trim() && isPublishTouched"
            class="text-danger mt-1"
          >
            练习名称不能为空
          </div>
        </div>

        <div class="mb-3">
          <label class="form-label">开始时间</label>
          <input 
            v-model="publishForm.startTime" 
            type="datetime-local" 
            class="form-control" 
            required
            @input="handleDateTimeInput('startTime')" 
            placeholder="YYYY-MM-DDThh:mm:ss"
            step="1"
          >
          <div
            v-if="isPublishTouched && (!publishForm.startTime || (publishForm.startTime && isNaN(new Date(publishForm.startTime).getTime())))"
            class="text-danger mt-1"
          >
            {{ !publishForm.startTime ? '请选择开始时间' : '请输入有效的开始时间格式' }}
          </div>
        </div>

        <div class="mb-3">
          <label class="form-label">截止时间</label>
          <input 
            v-model="publishForm.deadline" 
            type="datetime-local" 
            class="form-control" 
            required
            @input="handleDateTimeInput('deadline')" 
            placeholder="YYYY-MM-DDThh:mm:ss"
            step="1"
          >
          <div
            v-if="isPublishTouched && (!publishForm.deadline || (publishForm.deadline && isNaN(new Date(publishForm.deadline).getTime())))"
            class="text-danger mt-1"
          >
            {{ !publishForm.deadline ? '请选择截止时间' : '请输入有效的截止时间格式' }}
          </div>
          <div
            v-if="publishForm.startTime && publishForm.deadline && !isStartTimeBeforeDeadline()"
            class="text-danger mt-1"
          >
            开始时间不能晚于截止时间
          </div>
        </div>

        <div class="mb-3">
          <label class="form-label">允许多次提交</label>
          <select 
            v-model="publishForm.isMultipleSubmission" 
            class="form-control"
            @change="isPublishTouched = true" 
          >
            <option :value="true">
              是
            </option>
            <option :value="false">
              否
            </option>
          </select>
        </div>

        <!-- 已选题目预览 -->
        <div class="mt-4">
          <h4>已选题目（{{ selectedQuestions.length }}题）</h4>
          <div class="list-group">
            <div 
              v-for="(q, index) in selectedQuestions" 
              :key="index" 
              class="list-group-item"
            >
              <div>
                <h6>{{ q.questionContent }}</h6>
                <p>
                  类型：{{ q.type ? '主观题' : '选择题' }} | 
                  分值：{{ q.questionScore }}分
                </p>
              </div>
              <button 
                type="button" 
                class="btn btn-sm btn-danger" 
                @click="removeSelectedQuestion(index)"
              >
                删除
              </button>
            </div>
          </div>
          <div
            v-if="selectedQuestions.length === 0 && isPublishTouched"
            class="text-danger mt-2"
          >
            请至少选择1道题目
          </div>
        </div>

        <button 
          type="submit" 
          class="btn btn-primary mt-3" 
          :disabled="!isPublishFormValid || isSubmitting"
        >
          {{ isSubmitting ? '发布中...' : '确认发布练习' }}
        </button>
      </form>
    </div>

    <!-- 发布练习按钮 -->
    <div class="publish-exercise-btn">
      <button 
        class="btn btn-success" 
        :disabled="selectedQuestionIds.length === 0 || isLoading"
        @click="togglePublishPanel"
      >
        选择题目发布练习（已选 {{ selectedQuestionIds.length }} 题）
      </button>
    </div>

    <!-- 加载状态提示 -->
    <div
      v-if="isLoading || isSubmitting"
      class="loading-indicator"
    >
      <span
        class="spinner-border text-primary"
        role="status"
      >
        <span class="visually-hidden">加载中...</span>
      </span>
      <span
        v-if="isSubmitting"
        class="ms-2"
      >发布练习中...</span>
      <span
        v-if="isLoading"
        class="ms-2"
      >加载题目中...</span>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  props: {
    courseId: {
      type: String,
      required: true
    },
    classes: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      isLoading: false,
      isSubmitting: false,
      isPublishPanelOpen: false,
      isPublishTouched: false, // 记录发布表单是否被操作过
      newQuestion: {
        questionContent: '',
        questionAnswer: '',
        type: false, // 默认选择题
        questionScore: 10,
        options: ['', ''] // 初始两个选项
      },
      questions: [],
      selectedQuestionIds: [],
      publishForm: {
        exerciseName: '',
        startTime: '',
        deadline: '',
        isMultipleSubmission: true,
      },
      selectedClassId: ''
    };
  },
  computed: {
    selectedQuestions() {
      return this.questions.filter(question => 
        this.selectedQuestionIds.includes(question.questionId)
      );
    },
    isPublishFormValid() {
      // 验证开始时间和截止时间的有效性
      const isStartTimeValid = this.publishForm.startTime && !isNaN(new Date(this.publishForm.startTime).getTime());
      const isDeadlineValid = this.publishForm.deadline && !isNaN(new Date(this.publishForm.deadline).getTime());
      const isTimeOrderValid = isStartTimeValid && isDeadlineValid ? this.isStartTimeBeforeDeadline() : false;
      
      // 添加调试日志
      console.log('表单验证状态:', {
        touched: this.isPublishTouched,
        name: Boolean(this.publishForm.exerciseName.trim()),
        startTimeExists: Boolean(this.publishForm.startTime),
        startTimeValid: isStartTimeValid,
        deadlineExists: Boolean(this.publishForm.deadline),
        deadlineValid: isDeadlineValid,
        questions: this.selectedQuestions.length > 0,
        timeOrderValid: isTimeOrderValid,
        classId: Boolean(this.selectedClassId)
      });
      
      return (
        this.isPublishTouched &&
        this.publishForm.exerciseName.trim() &&
        isStartTimeValid &&
        isDeadlineValid &&
        this.selectedQuestions.length > 0 &&
        isTimeOrderValid &&
        this.selectedClassId // 班级选择校验
      );
    }
  },
  mounted() {
    this.loadQuestions();
    // 初始化选择第一个班级（如果有）
    if (this.classes.length > 0) {
      this.selectedClassId = this.classes[0].classesId;
    }
  },
  methods: {
    // 加载题库题目
    async loadQuestions() {
      try {
        this.isLoading = true;
        const response = await axios.get(
          `/api/exercises/bank/${this.courseId}/questions`
        );
        this.questions = response.data;
      } catch (error) {
        console.error('加载题目失败:', error);
        alert('加载题目失败，请检查网络连接');
      } finally {
        this.isLoading = false;
      }
    },

    // 添加题目
    async handleAddQuestion() {
      if (!this.newQuestion.type && this.newQuestion.options.some(opt => !opt.trim())) {
        alert('选择题选项不能为空');
        return;
      }

      // 格式化题目内容（添加选项）
      if (!this.newQuestion.type) {
        this.newQuestion.questionContent = `${this.newQuestion.questionContent}\n${this.newQuestion.options.map((opt, idx) => 
          `${this.getOptionLabel(idx)}. ${opt}`
        ).join('\n')}`;
      }

      try {
        this.isLoading = true;
        const questionToAdd = {
          ...this.newQuestion,
          options: this.newQuestion.type ? [] : this.newQuestion.options,
          exerciseId: this.$route.query.exerciseId || null // 添加exerciseId参数
        };

        const response = await axios.post(
          `/api/exercises/bank/${this.courseId}/questions`,
          questionToAdd
        );
        this.questions.push(response.data);
        this.resetNewQuestion();
        alert('题目添加成功');
      } catch (error) {
        console.error('添加题目失败:', error);
        alert('添加题目失败，请检查输入内容');
      } finally {
        this.isLoading = false;
      }
    },
    // 切换题目类型时重置选项
    handleTypeChange() {
      if (this.newQuestion.type) {
        this.newQuestion.options = []; // 主观题清空选项
      } else {
        this.newQuestion.options = this.newQuestion.options.length < 2 ? ['', ''] : this.newQuestion.options; // 确保至少两个选项
      }
    },
    // 删除题目
    async handleDeleteQuestion(questionId) {
      if (!confirm('确定要删除该题目吗？')) return;

      try {
        this.isLoading = true;
        await axios.post(
          `/api/exercises/bank/${this.courseId}/questions/${questionId}`
        );
        this.questions = this.questions.filter(q => q.questionId !== questionId);
        alert('题目删除成功');
      } catch (error) {
        console.error('删除题目失败:', error);
        alert('删除题目失败，请重试');
      } finally {
        this.isLoading = false;
      }
    },

    // 切换发布面板
    togglePublishPanel() {
      this.isPublishPanelOpen = !this.isPublishPanelOpen;
      this.isPublishTouched = false; // 关闭时重置操作状态
      if (this.isPublishPanelOpen) {
        // 初始化时间字段（当前时间 + 7天）
        const now = new Date();
        
        // 格式化为yyyy-MM-dd HH:mm:ss格式，确保与后端期望格式兼容
        const formatDateForBackend = (date) => {
          const pad = (num) => (num < 10 ? '0' + num : num);
          return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
        };
        
        // 格式化为YYYY-MM-DDThh:mm:ss格式，确保与datetime-local输入字段兼容
        const formatDateForInput = (date) => {
          const pad = (num) => (num < 10 ? '0' + num : num);
          return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
        };
        
        const startDate = new Date(now.getTime());
        const deadlineDate = new Date(now.getTime() + 7 * 24 * 3600 * 1000);
        
        // 使用T分隔符格式用于前端输入字段
        this.publishForm.startTime = formatDateForInput(startDate);
        this.publishForm.deadline = formatDateForInput(deadlineDate);
        
        console.log('初始化开始时间:', this.publishForm.startTime);
        console.log('初始化截止时间:', this.publishForm.deadline);
        console.log('后端格式开始时间:', formatDateForBackend(startDate));
        console.log('后端格式截止时间:', formatDateForBackend(deadlineDate));
      }
      if (this.isPublishPanelOpen && this.classes.length > 0) {
        // 自动选择第一个班级
        this.selectedClassId = this.classes[0].classesId;
      }
    },

    // 移除选中题目
    removeSelectedQuestion(index) {
      const questionId = this.selectedQuestions[index].questionId;
      this.selectedQuestionIds = this.selectedQuestionIds.filter(id => id !== questionId);
    },

    async handlePublish() {
      this.isPublishTouched = true;
      if (!this.isPublishFormValid) return;

      this.isSubmitting = true;
      try {
        // 构造符合ExerciseCreateDto的请求体
        // 确保日期时间格式符合后端要求 (yyyy-MM-dd HH:mm:ss)
        const formatDateTime = (dateTimeStr) => {
          console.log('格式化前的日期时间字符串:', dateTimeStr, '类型:', typeof dateTimeStr);
          if (!dateTimeStr) {
            console.log('日期时间为空，返回空字符串');
            return '';
          }
          
          try {
            // 尝试解析日期，无论输入格式如何
            const date = new Date(dateTimeStr);
            const timestamp = date.getTime();
            console.log('解析后的时间戳:', timestamp, '是否有效:', !isNaN(timestamp));
            
            if (isNaN(timestamp)) {
              console.error('无效的日期时间格式:', dateTimeStr);
              return dateTimeStr; // 无法解析时返回原始值
            }
            
            // 格式化为后端期望的格式：yyyy-MM-dd HH:mm:ss
            const pad = (num) => (num < 10 ? '0' + num : num);
            const formattedDate = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
            console.log('格式化后的日期时间:', formattedDate);
            return formattedDate;
          } catch (error) {
            console.error('日期时间格式化错误:', error);
            return dateTimeStr; // 出错时返回原始值
          }
        };
        
        // 确保日期时间格式符合ISO 8601标准，后端LocalDateTime可以正确解析
        const requestBody = {
          exerciseName: this.publishForm.exerciseName,
          exerciseStartTime: formatDateTime(this.publishForm.startTime),
          exerciseDeadline: formatDateTime(this.publishForm.deadline),
          classesId: this.selectedClassId,
          isMultipleSubmission: this.publishForm.isMultipleSubmission,
          exerciseScore: this.calculateTotalScore()
        };
        
        // 打印日期时间格式，用于调试
        console.log('格式化后的开始时间:', requestBody.exerciseStartTime);
        console.log('格式化后的截止时间:', requestBody.exerciseDeadline);
        
        console.log('提交的练习数据:', JSON.stringify(requestBody, null, 2));

        // 第一步：创建练习
        const response = await axios.post('/api/exercises', requestBody);
        
        if (response.status !== 201) {
          throw new Error(response.data.message || '创建练习失败');
        }
        
        const createdExercise = response.data;
        const exerciseId = createdExercise.exerciseId;
        
        // 第二步：关联题目（直接使用已有题目ID，不重新创建题目）
        const promises = this.selectedQuestions.map(question => {
          // 只发送题目ID和练习ID，后端会建立关联而不是重新创建题目
          return axios.post(`/api/exercises/${exerciseId}/questions/${question.questionId}`);
        });
        
        await Promise.all(promises);
        if (response.status === 201) {
          alert('练习发布成功！');
          this.resetPublishState();
        } else {
          alert(`发布失败：${response.data.message || '后端错误'}`);
        }
      } catch (error) {
        console.error('发布练习失败:', error.response?.data || error);
        alert('发布失败，请检查参数或联系管理员');
      } finally {
        this.isSubmitting = false;
      }
    },
    generateExerciseId() {
      return `EX-${Date.now().toString(36)}-${Math.random().toString(36).substr(2, 5)}`;
    },
        // 计算总分
    calculateTotalScore() {
      return this.selectedQuestions.reduce((sum, q) => sum + q.questionScore, 0);
    },
    // 输入内容时触发触达状态
    handleQuestionContentInput() {
      this.isQuestionTouched = true;
    },

    handleOptionInput() {
      this.isQuestionTouched = true;
    },
    
    // 处理日期时间输入，确保格式正确
    handleDateTimeInput(field) {
      this.isPublishTouched = true;
      
      // 输出原始值用于调试
      console.log(`处理${field}字段，原始值:`, this.publishForm[field]);
      
      // 如果输入为空，直接返回
      if (!this.publishForm[field]) {
        console.log(`${field}字段为空`);
        return;
      }
      
      // 确保日期时间格式包含秒部分
      if (this.publishForm[field].length === 16) {
        this.publishForm[field] = this.publishForm[field] + ':00';
        console.log(`添加秒部分后:`, this.publishForm[field]);
      }
      
      // 验证日期格式是否有效
      const dateObj = new Date(this.publishForm[field]);
      const isValid = !isNaN(dateObj.getTime());
      console.log(`转换为Date对象:`, dateObj, `是否有效:`, isValid);
      
      // 如果日期无效，尝试修复或提示用户
      if (!isValid) {
        console.error(`${field}日期格式无效`);
        // 可以在这里添加额外的处理逻辑，比如重置为当前时间
        // this.publishForm[field] = new Date().toISOString().slice(0, 19);
      } else {
        // 确保格式为YYYY-MM-DDThh:mm:ss (ISO格式，适用于datetime-local输入字段)
        const date = new Date(this.publishForm[field]);
        const pad = (num) => (num < 10 ? '0' + num : num);
        const formattedDate = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
        console.log(`重新格式化为ISO格式:`, formattedDate);
        this.publishForm[field] = formattedDate;
      }
    },
    
    // 比较开始时间和截止时间
    isStartTimeBeforeDeadline() {
      if (!this.publishForm.startTime || !this.publishForm.deadline) {
        console.log('开始时间或截止时间为空，无法比较');
        return false;
      }
      
      // 确保两个日期时间字符串都包含秒部分
      const startTime = this.publishForm.startTime.length === 16 ? 
        this.publishForm.startTime + ':00' : this.publishForm.startTime;
      const deadline = this.publishForm.deadline.length === 16 ? 
        this.publishForm.deadline + ':00' : this.publishForm.deadline;
      
      console.log('比较日期:', { startTime, deadline });
      
      // 验证日期格式是否有效
      const startDate = new Date(startTime);
      const deadlineDate = new Date(deadline);
      const startTimestamp = startDate.getTime();
      const deadlineTimestamp = deadlineDate.getTime();
      const isStartValid = !isNaN(startTimestamp);
      const isDeadlineValid = !isNaN(deadlineTimestamp);
      
      console.log('日期有效性:', { isStartValid, isDeadlineValid });
      console.log('时间戳比较:', { startTimestamp, deadlineTimestamp });
      
      // 如果任一日期无效，返回false
      if (!isStartValid || !isDeadlineValid) {
        console.error('日期格式无效，无法比较');
        return false;
      }
      
      // 使用时间戳比较而不是字符串比较
      const result = startTimestamp < deadlineTimestamp;
      console.log('比较结果:', result);
      return result;
    },
    // 重置题目表单
    resetNewQuestion() {
      this.newQuestion = {
        questionContent: '',
        questionAnswer: '',
        type: false,
        questionScore: 10,
        options: ['', '']
      };
    },
    // 重置发布状态
    resetPublishState() {
      this.isPublishPanelOpen = false;
      this.selectedQuestionIds = [];
      this.publishForm = {
        exerciseName: '',
        startTime: '',
        deadline: '',
        isMultipleSubmission: true
      };
      // 重置后如果再次打开面板，togglePublishPanel方法会初始化日期时间
    },
    // 生成选项标签（A/B/C等）
    getOptionLabel(index) {
      return String.fromCharCode('A'.charCodeAt(0) + index);
    },

    // 添加选项
    addOption() {
      this.newQuestion.options.push('');
    },

    // 删除选项
    removeOption(index) {
      if (this.newQuestion.options.length > 2) {
        this.newQuestion.options.splice(index, 1);
      }
    }
  }
}
</script>

<style scoped>
/* 新增选项样式 */
.input-group {
  margin-bottom: 0.5rem;
}

.input-group-text {
  width: 30px;
  text-align: center;
}

/* 发布面板样式 */
.publish-exercise-panel {
  margin-top: 3rem;
  padding: 2rem;
  background: #f8f9fa;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* 错误提示样式 */
.text-danger {
  color: #dc3545;
  font-size: 0.875rem;
  margin-top: 0.25rem;
}

/* 加载状态样式 */
.loading-indicator {
  margin-top: 1rem;
  display: flex;
  align-items: center;
  color: #6c757d;
}

/* 原有容器样式 */
.exercise-bank-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

/* 按钮样式 */
.btn-success {
  background-color: #28a745;
  border-color: #28a745;
}

.btn-danger {
  background-color: #dc3545;
  border-color: #dc3545;
}

.btn {
  margin-right: 0.5rem;
  padding: 0.375rem 0.75rem;
  border-radius: 0.25rem;
}
</style>
